import { httpReqeustApi } from '/@/api/linxyun/base/index.ts';
const httpRequest = httpReqeustApi();
import { createDDE_SA } from '/@/utils/stringUtil';

const DDE_SA = createDDE_SA(BASE_API.ENT_CODE || 0, 0, 0);
const headers = { 'DDE-SA': DDE_SA, 'Content-Type': 'application/json;charset=UTF-8' };
// import { getPageInfo, getPageCpns } from './query'
class EnumOptions {
	_isLoaded = false;
	_options = {}; // enum name ---> options
	static _instance = null;
	static instance() {
		if (this._instance === null) {
			this._instance = new EnumOptions();
		}

		return this._instance;
	}
	// 返回 enumName 对应的 可选项
	getOptions(enumName) {
		if (localStorage.getItem('options') && (JSON.stringify(this._options) === '{}' || !this._options)) {
			this._options = JSON.parse(localStorage.getItem('options'));
		}
		if (!this._isLoaded && (JSON.stringify(this._options) === {} || !this._options)) {
			return null;
		}
		if (this._options[enumName]) {
			return this._options[enumName];
		}

		console.error('[Error][EnumOptions][getOptions]Enum is not exist, enum: ', enumName);
		return null;
	}
	getOptionLabel(enumName, value) {
		let options = this.getOptions(enumName);
		if (!options) {
			return null;
		}
		for (let i = 0; i < options.length; i++) {
			if (options[i].value === value) {
				return options[i].label;
			}
		}
		return null;
	}
	async loadEnumOptions() {
		if (this._isLoaded) {
			return;
		}
		console.log('[Debug][EnumOptions]Load enum options');
		const params = { EntCode: BASE_API.ENT_CODE, current: 0, limit: 500 };
		let res = await httpRequest.Post('/eslithe/queryEnumOptionsNew.action', null, params, headers);
		if (!res || res.code !== '0000') {
			console.error('[Error][EnumOptions][loadEnumOptions]load fail, res: ', res);
			return;
		}

		if (!res.Records || res.Records.length === 0) {
			console.error('[Error][EnumOptions][loadEnumOptions]No enum defined.');
			return;
		}

		for (let i = 0; i < res.Records.length; i++) {
			if (!res.Records[i].EnumName || res.Records[i].EnumName === '') {
				console.error('[Error][EnumOptions][loadEnumOptions]The enum is empty: ', res.Records[i]);
				continue;
			}
			if (!res.Records[i].Options || res.Records[i].Options === '') {
				console.error('[Error][EnumOptions][loadEnumOptions]The enum options no defined: ', res.Records[i]);
				continue;
			}
			// console.log('000000000000000000: ', res.Records[i].Options, res.Records[i].Options.replace(/\\/g, ''));
			const options = JSON.parse(res.Records[i].Options.replace(/\\/g, ''));
			if (!options || options.length === 0) {
				console.error('[Error][EnumOptions][loadEnumOptions]The enum options no defined: ', res.Records[i]);
				continue;
			}
			this._options[res.Records[i].EnumName] = options;
		}
		// console.log('loadEnumOptions', this._options);
		localStorage.setItem('options', JSON.stringify(this._options));
		this._isLoaded = true;
	}
}

export default EnumOptions;
